import { useUserStore } from '@/store/userStore'

// 不需要登录的页面白名单
const whiteList = [
  '/pages/index/index',
  '/pages/category/category',
  '/pages/login/login'
]

// tabBar 页面列表
const tabBarPages = [
  '/pages/index/index',
  '/pages/category/category',
  '/pages/cart/cart',
  '/pages/user/user'
]

// 检查是否是 tabBar 页面
const isTabBarPage = (path) => {
  return tabBarPages.some(tabPath => path.startsWith(tabPath))
}

// 检查是否需要登录
export const checkNeedLogin = (path) => {
  if (!path) return false;
  return !whiteList.some(whitePath => path.startsWith(whitePath))
}

// 检查登录状态并处理路由
export const checkLoginAndRedirect = (path) => {
  const userStore = useUserStore()
  
  // 如果是白名单页面，直接通过
  if (!checkNeedLogin(path)) {
    return true
  }

  // 获取并检查token
  const token = getToken()
  if (!token) {
    handleNotLoggedIn(path)
    return false
  }

  // 检查登录状态
  const isLoggedIn = userStore.checkLogin()
  if (!isLoggedIn) {
    handleNotLoggedIn(path)
    return false
  }
  
  return true
}

// 处理未登录状态
const handleNotLoggedIn = (path) => {
  // 获取当前页面路径
  const currentPath = path || getCurrentPagePath()
  
  // 跳转到登录页面，并携带当前页面的路径
  if (isTabBarPage(currentPath)) {
    // 如果是 tabBar 页面，登录后需要使用 switchTab
    uni.navigateTo({
      url: `/pages/login/login?redirect=${encodeURIComponent(currentPath)}&type=switchTab`
    })
  } else {
    uni.navigateTo({
      url: `/pages/login/login?redirect=${encodeURIComponent(currentPath)}`
    })
  }
}

// 获取当前页面路径
export const getCurrentPagePath = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const { route, options } = currentPage
  
  // 构建完整路径（包含参数）
  let path = '/' + route
  const queryArr = []
  for (const key in options) {
    queryArr.push(`${key}=${options[key]}`)
  }
  if (queryArr.length) {
    path += '?' + queryArr.join('&')
  }
  
  return path
}

// 获取token
export const getToken = () => {
  return uni.getStorageSync('token');
};

// 设置token
export const setToken = (token) => {
  uni.setStorageSync('token', token);
};

// 移除token
export const removeToken = () => {
  uni.removeStorageSync('token');
};

// 简单检查是否登录（仅检查token是否存在）
export const checkLogin = () => {
  const token = getToken();
  return !!token;
}; 